package com.starview.star.compiler.cafe.compile;

import com.starview.platform.data.type.IType;
import com.starview.platform.data.type.Location;
import com.starview.star.code.repository.CodeCatalog;
import com.starview.star.compiler.ErrorReport;
import com.starview.star.compiler.util.AccessMode;
import org.objectweb.asm.tree.InsnList;
import org.objectweb.asm.tree.LabelNode;
import org.objectweb.asm.tree.LocalVariableNode;
import org.objectweb.asm.tree.MethodNode;

public class LocalDefiner implements Definer{
  protected final LabelNode endLabel;
  protected final CodeContext ccxt;
  protected final CodeCatalog bldCat;

  public LocalDefiner(LabelNode endLabel, CodeContext ccxt){
    this.endLabel = endLabel;
    this.ccxt = ccxt;
    this.bldCat = ccxt.getBldCat();
  }

  @Override
  public VarInfo declareArg(Location loc, String name, int varOffset, IType varType, CafeDictionary dict,
                            AccessMode access, boolean isInited, ErrorReport errors){
    MethodNode mtd = ccxt.getMtd();

    ISpec vrSpec = SrcSpec.generic(loc, varType, dict, bldCat, errors);

    VarInfo var = dict.declareLocal(name, vrSpec, isInited, access);

    if (isInited) {
      LabelNode startLabel = new LabelNode();
      mtd.localVariables.add(new LocalVariableNode(var.getJavaSafeName(), var.getJavaSig(), null, startLabel, endLabel,
              var.getOffset()));
      InsnList ins = mtd.instructions;
      ins.add(startLabel);
    }
    return var;
  }
}